#include <string.h>
#include <stdlib.h>
#include "usersLoad.h"

int usercount;

int loadUsers(char const *filename,struct UserVars **data_ptr){
	FILE *ptr_file;///create FILE pointer
	ptr_file=fopen(filename,"r");///open file specified in *filename
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;///used to allocate buffer length
	int numlines=getFileInfo(ptr_file,&maxlinelen);///used to allocate users array size
	usercount=numlines;
	struct UserVars *data;
	data=(struct UserVars*) calloc(numlines,sizeof(struct UserVars));///allocate user array
	char *buf=(char*) malloc(maxlinelen*sizeof(char));///allocate buffer size
	char *tmp=(char*) malloc(20*sizeof(char));

	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);///load a line to buffer
		sscanf(strtok(buf,"-"), "%d", &data[i].userID);
		strcpy(data[i].name,strtok(NULL,"-"));
		strcpy(data[i].userType,strtok(NULL,"-"));
		strcpy(data[i].user,strtok(NULL,"-"));
		strcpy(data[i].password,strtok(NULL,"\n"));
	}
	free(buf);
	fclose(ptr_file);
	*data_ptr=data;
	return 0;
}

int writeUsers(char const *filename,struct UserVars *data){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	///loop through users
	for(int i=0;i<usercount;i++){
		///print a line
		fprintf(ptr_file,"%02d-%s-%s-%s-%s\n",data[i].userID,data[i].name,data[i].userType,data[i].user,data[i].password);
	}
	fclose(ptr_file);
	free(data);
	return 0;
}


void addUser(struct UserVars n,struct UserVars **data_ptr){
	///reallocate user array size and increment usercount
	struct UserVars *data;
	data=(struct UserVars*) realloc(*data_ptr,++usercount*sizeof(struct UserVars));
	data[usercount-1]=n;
	*data_ptr=data;
}

void rmUser(int index,struct UserVars **data_ptr){
	struct UserVars *data=(struct UserVars*) calloc(usercount-1,sizeof(struct UserVars));///allocate new array with one less element
	if(index!=0){
		memcpy(data,*data_ptr,index*sizeof(struct UserVars));
	}
	//copy everything after index
	if(index < usercount){
		memcpy(data + index,*data_ptr + index + 1,(usercount - index - 1)*sizeof(struct UserVars));
	}
	usercount--;
	free(*data_ptr);
	*data_ptr=data;
}
